import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import {
  Badge,
  Button,
  Card,
  Col,
  Divider,
  Dropdown,
  Form,
  Icon,
  Input,
  InputNumber,
  Menu,
  Modal,
  Radio,
  Row,
  Select,
} from 'antd';
import TableList from '@/components/TableList';
import styles from '../search.less';
import {nameMaxLength, remarkMaxLength, ruleP} from '@/utils/rule'

const {TextArea} = Input;
const FormItem = Form.Item;
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];

const formLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};
const CreateForm = Form.create()(props => {
  const {modalVisible, form, addDataFn, updateFn, handleModalVisible, text, listNameData} = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if (text) {
        updateFn(fieldsValue, text)
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑字典数据' : '新增字典数据'}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="数据编码">
        {form.getFieldDecorator('dicCode', {
          rules: [{required: true, whitespace:true, message: '数据编码不能为空'},
            {pattern: new RegExp(ruleP(1)[0], 'g'), message: ruleP(1)[1]}, {max: 60, message: "字符长度不能60"}],
          initialValue: text && text.dataDictCode || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="数据名称">
        {form.getFieldDecorator('dicName', {
          rules: [{required: true, whitespace:true, message: '数据名称不能为空'}, {max: nameMaxLength()[0], message: nameMaxLength()[1]}],
          initialValue: text && text.dataDictName || ''
        })(<Input placeholder="请输入"/>)}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="字典类型">
        {form.getFieldDecorator('dicTypeName', {
          rules: [{required: true, message: '字典类型不能为空'}], initialValue: text && text.dataDictTypeCode
        })(<Select placeholder="请选择" style={{width: '100%'}}>
          {
            listNameData && listNameData.length && listNameData.map((v, i) => {
              return (<Option value={v.value}>{v.name}</Option>)
            })
          }
        </Select>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="内容">
        {form.getFieldDecorator('keyValue', {
          rules: [{required: true, whitespace:true, message: '内容不能为空'}, {max: remarkMaxLength()[0], message: remarkMaxLength()[1]}],
          initialValue: text && text.dataDictValue || ''
        })(
          <TextArea placeholder="请输入" style={{minHeight: 32}} rows={2}/>
        )}
      </FormItem>
      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="排序">
        {form.getFieldDecorator('sortNum', {initialValue: text && text.orderNum || ''})(<InputNumber placeholder="1"
                                                                                                     min={1}
                                                                                                     style={{width: '100%'}}/>)}
      </FormItem>

      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="状态"
                style={{display: text == null ? 'none' : 'block',}}>
        {form.getFieldDecorator('status', {
          initialValue: text && text.status
        })(<Radio.Group>
          <Radio value={0}>
            启用
          </Radio>
          <Radio value={1}>
            禁用
          </Radio>
        </Radio.Group>)}
      </FormItem>


      <FormItem labelCol={{span: 5}} wrapperCol={{span: 19}} label="备注">
        {form.getFieldDecorator('note', {
          rules: [{max: remarkMaxLength()[0], message: remarkMaxLength()[1]}],
          initialValue: text && text.remark || ''
        })(<TextArea
          style={{minHeight: 32}}
          rows={2}
        />)}
      </FormItem>
    </Modal>
  );
});


@connect(({dicName, loading}) => ({
  dicName,
  loading: loading.models.dicName,
}))

@Form.create()
class dicNameList extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    formValues: {},
    expandForm: false,
    selectedRows: [],
    text: {},
    listNameData: [],
    detailVisible: false,
    detailsData: {},
  };

  columns = [
    {
      title: '数据名称',
      dataIndex: 'dataDictName',
    },
    {
      title: '字典类型',
      dataIndex: 'dataDictTypeName',
    },
    {
      title: '内容',
      dataIndex: 'dataDictValue',
      width: '40%',
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
      /*render: (text) => (
        <div style={{ whiteSpace: 'nowrap', overflow: 'hidden',textOverflow:'ellipsis' }} title={{text}}>
          {text}
        </div>
      )*/
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.detailHandelVisible(true, text)}>详情</a>
          <Divider type="vertical"/>
          {text.isDefault == 0 ? (
            <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>
          ) : (
            <Dropdown
              overlay={
                <Menu>
                  <Menu.Item onClick={() => this.handleModalVisible(true, text)}>编辑</Menu.Item>
                  <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
                </Menu>
              }
            >
              <a>更多 <Icon type="down"/></a>
            </Dropdown>

          )}
        </Fragment>
      ),
    },
  ];

  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };

  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  // 删除方法
  handleDeleteData(id) {
    const {dispatch} = this.props;
    const {formValues} = this.state;
    const values = {
      id
    };

    dispatch({
      type: 'dicName/remove',
      payload: values,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues);
          this.setState({selectedRows: []})
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  //详情
  detailHandelVisible = (flag, text) => {
    this.setState({
      detailVisible: !!flag,
      detailsData: text,
    });
  };

  // 分页查询列表
  pageList(dataDict, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    const values = {
      dataDictName: dataDict && dataDict.dicName || '',
      dataDictTypeName: dataDict && dataDict.dicTypeName || '',
      dataDictCode: dataDict && dataDict.dicCode || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'dicName/queryList',
      payload: values,
    });
  }

  // 字典类型
  selectList() {
    const {dispatch} = this.props;
    dispatch({
      type: 'dicName/selectList',
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            listNameData: res.data.dataList
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  componentDidMount() {
    this.pageList();
    this.selectList();//字典类型
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      })
      //点击查询
      this.pageList(fieldsValue);
    });
  };

// 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text
    });
  };

  // 更新接口
  updateFn = (fields, text) => {
    const {dispatch, dicName: {data},} = this.props;
    const {formValues} = this.state;
    let pageNum = data.pageNum;
    let pageSize = data.pageSize;

    const params = {
      id: text.id,
      dataDictCode: fields.dicCode,
      dataDictTypeCode: fields.dicTypeName,
      dataDictName: fields.dicName,
      dataDictValue: fields.keyValue,
      /*    restartEffect:fields.isRestart,*/
      remark: fields.note,
      orderNum: fields.sortNum,
      status: fields.status,
    }
    dispatch({
      type: 'dicName/update',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues,pageSize,pageNum);
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;
    const params = {
      dataDictCode: fields.dicCode,//字典CODE
      dataDictTypeCode: fields.dicTypeName,//据字典类别
      dataDictName: fields.dicName,//字典名称
      dataDictValue: fields.keyValue,//字典值
      /* restartEffect:fields.isRestart,//重启生效 0：否 1：是*/
      remark: fields.note,//备注
      orderNum: fields.sortNum,//排序
      status: fields.status, //0正常1禁用
    }
    dispatch({
      type: 'dicName/add',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.pageList(formValues);
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
    this.handleModalVisible();
  };
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置
  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="数据名称">
              {getFieldDecorator('dicName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="字典类型">
              {getFieldDecorator('dicTypeName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const {expandForm} = this.state;
    return expandForm ? this.renderSimpleForm() : this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  render() {
    const {
      dicName: {data},
      loading,
    } = this.props;
    const {selectedRows, modalVisible, updateModalVisible, text, listNameData, detailVisible, detailsData} = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
      </Menu>
    );
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn
    };

    const detailsMethods = {
      detailHandelVisible: this.detailHandelVisible,
    };

    return (
      <Card bordered={false}>
        <CreateForm {...parentMethods} modalVisible={modalVisible} text={text} listNameData={listNameData}/>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
              新增
            </Button>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange.bind(this)}
            rowKey={record => record.id}
          />
        </div>

        {detailsData && detailsData.id ? (
          <Details {...detailsMethods} detailVisible={detailVisible} detailsData={detailsData}/>
        ) : null}
      </Card>
    );
  }
}


class Details extends PureComponent {
  render() {
    const {detailVisible, detailHandelVisible, detailsData} = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailVisible}
        onOk={() => detailHandelVisible()}
        onCancel={() => detailHandelVisible()}
        footer={[
          <Button key="back" type="primary" onClick={() => detailHandelVisible()}>返回</Button>
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={12}>
            <FormItem {...formLayout} label="数据名称">
              {detailsData.dataDictName}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="数据编码">
              {detailsData.dataDictCode}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="字典类型">
              {detailsData.dataDictTypeName}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...formLayout} label="字典类型编码">
              {detailsData.dataDictTypeCode}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="排序">
              {detailsData.orderNum}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="内容">
              {detailsData.dataDictValue}
            </FormItem>
          </Col>

          <Col md={24}>
            <FormItem labelCol={{span: 3}} wrapperCol={{span: 21}} label="备注">
              {detailsData.remark}
            </FormItem>
          </Col>

        </Row>
      </Modal>
    );
  }
}

export default dicNameList;
